package www.lagou.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.PrimitiveIterator;
import java.util.Properties;

/**
 * @author cyt
 * @date 2020/7/12
 */
public class DruidUtils {

    public static DataSource dataSource;

    static{

        try {
            Properties p = new Properties();

            InputStream inputStream = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties");

            p.load(inputStream);

            dataSource = DruidDataSourceFactory.createDataSource(p);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public static Connection getConnection(){
        try {
            return (Connection) dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static DataSource getDataSource(){
        return dataSource;
    }

    public static void close(Connection con, Statement s) throws SQLException {
        if( con != null && s != null ){
            try {
                s.close();
                con.close();
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection con, Statement s, ResultSet resultSet){
        if( con != null && s != null && resultSet != null ){
            try {
                resultSet.close();
                s.close();
                con.close();
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
    }
}
